<template>
    <div class="join-drgs-container">
        <global-search @submitSearch="submitSearch" :showDep="false" class="global-tool-search">
            <template slot="tool-box">
                <el-button type="text" @click="showDialog" v-auth="{code: 200005001001}">
                    <svg-icon icon-class="export"/>
                    导入
                </el-button>
            </template>
        </global-search>
        <div class="tables-box">
            <el-table
                border
                :data="tableData"
                :max-height="tableHeight"
                tooltip-effect="light"
                style="width: 100%"
                :empty-text="emptyText"
                @sort-change="sortChange">
                <el-table-column
                    show-overflow-tooltip
                    prop="date"
                    align="center"
                    type="index"
                    label="序号"
                    width="50">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="fileName"
                    align="left"
                    label="文件名"
                    min-width="200">
                    <template slot-scope="scope">
                        <el-button type="text" @click="toBillingList(scope.row, 1)">
                            {{scope.row.fileName}}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="medicalSum"
                    align="center"
                    label="病案数"
                    min-width="100">
                    <template slot-scope="scope">
                        <el-button type="text" @click="toBillingList(scope.row, 1)">
                            {{scope.row.medicalSum}}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="trueSum"
                    align="center"
                    label="正常对比"
                    min-width="100">
                    <template slot-scope="scope">
                        <el-button type="text" @click="toCompareResults(scope.row)">
                            {{scope.row.trueSum}}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="falseSum"
                    align="center"
                    label="异常对比"
                    min-width="100">
                    <template slot-scope="scope">
                        <el-button type="text" @click="toBillingList(scope.row, 2)">
                            {{scope.row.falseSum}}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="createTime"
                    align="center"
                    sortable="custom"
                    label="导入时间"
                    min-width="140">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="createUserName"
                    align="center"
                    label="操作人"
                    min-width="80">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="state"
                    align="center"
                    label="导入状态"
                    min-width="90">
                    <template slot-scope="scope">
                        <el-progress v-if="scope.row.state === 1" :text-inside="true" :stroke-width="16" :percentage="scope.row.progrossValue"></el-progress>
                        <span v-else :class="{
                        'status-yellow': scope.row.state === 1,
                        'status-green': scope.row.state === 2,
                        'status-red': scope.row.state === 0}">
                            {{scope.row.state | getState}}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="info"
                    align="left"
                    label="提示"
                    min-min-width="110">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    label="操作"
                    align="center"
                    fixed="right"
                    min-width="50">
                    <template slot-scope="scope">
                        <el-button v-auth="{code: 200005001002}" type="text"
                                   @click="deleteRow(scope.$index, scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="tableData.length > 0" :total="total" :page.sync="currentPage" :limit.sync="pageSize"
                        @pagination="changePage"/>
        </div>
        <el-dialog
            title="导入结算结果"
            :visible.sync="dialogVisible"
            :close-on-click-modal="false"
            width="30%"
            center
            :before-close="handleClose">
            <div class="content">
                <div class="template-box">
                    <p><i class="el-icon-warning"></i><span>请导入医保标准结算结果列表文件</span></p>
                    <el-button type="text" size="small" @click="downloadTemplate" icon="el-icon-download">下载模板
                    </el-button>
                </div>
                <upload-file
                    :drag="true"
                    :limit="limit"
                    accept=".xls,.xlsx"
                    :noPrompt="true"
                    :fileList="fileList"
                    @removeFile="removeFile">
                </upload-file>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="submitFileList">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {groupUploadFiles, getImportList, delImportList} from '@/api/group-compare/import-settle'
    import {getSortString} from '@/utils/filters'
    import uploadFile from '@/components/Upload'
    import * as signalR from '@microsoft/signalr'

    export default {
        name: 'index',
        data () {
            return {
                form: {},
                // 当前页
                currentPage: 1,
                // 每页数量
                pageSize: 20,
                // 表格高度
                tableHeight: 0,
                // 全部表格数据
                tableData: [],
                // 数据总数
                total: 0,
                // 显示弹框
                dialogVisible: false,
                // 最大上传数
                limit: 5,
                // 文件列表
                fileList: [],
                // 上传数据id
                fileDataId: '',
                // 全局搜索内容，用于翻页等不传参时使用数据
                globalForm: {},
                // 排序字段
                sortMap: {},
                // 排序方式
                sortType: '',
                // 空数据时显示的文本内容
                emptyText: '暂无数据',
                // 使用储存的数据，不去请求
                useStore: false
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStore = this.$route.query.tags === 'tags'
            this.initPage()
            // 头部40 + 快捷标签30 + 面包屑30 + 搜索框42 + 分页64 + 底部padding10 + 表格上面和灰色背景的空白10px
            let height = document.documentElement.clientHeight - 100 - 42 - 64 - 10 - 10
            this.tableHeight = height > 108 ? height : 108
        },
        mounted () {
            let searchHeight = document.getElementsByClassName('global-tool-search')[0].offsetHeight
            if (searchHeight > 42) {
                let height = document.documentElement.clientHeight - 100 - searchHeight - 64 - 10 - 10
                this.tableHeight = height > 108 ? height : 108
            }
            this.joinSRG()
            // 白色背景高度
            document.getElementsByClassName('tables-box')[0].style.height = this.tableHeight + 64 + 10 + 'px'
            // 分页组件位置，不能使用bottom = 0，当位置发生变化时会出错
            document.getElementsByClassName('pagination-container')[0].style.top = this.tableHeight + 10 + 'px'
            window.onresize = () => {
                let height = document.documentElement.clientHeight - 100 - searchHeight - 64 - 10 - 10
                this.tableHeight = height > 108 ? height : 108
                document.getElementsByClassName('tables-box')[0].style.height = this.tableHeight + 64 + 10 + 'px'
                document.getElementsByClassName('pagination-container')[0].style.top = this.tableHeight + 10 + 'px'
            }
        },
        methods: {
            /**
             * 连接srg
             */
            joinSRG () {
                let hubUrl = window.location.href.includes('localhost') ? 'http://192.168.0.50/mc/commandhub' : '/mc/commandhub'
                let connection = new signalR.HubConnectionBuilder().withAutomaticReconnect().withUrl(hubUrl).build()
                connection.start().catch()
                connection.on('broadcast', (msg) => {
                    let kind = msg.kind
                    let body = JSON.parse(msg.body)
                    if (kind === 3) {
                        if (this.tableData.filter(item => item.id === body.pack.id).length) {
                            this.tableData.forEach(item => {
                                if (item.id === body.pack.id) {
                                    item.fileName = body.pack.fileName
                                    item.medicalSum = body.pack.medicalSum
                                    item.trueSum = body.pack.trueSum
                                    item.falseSum = body.pack.falseSum
                                    item.createTime = body.pack.createTime
                                    item.createUserName = body.pack.createUserName
                                    item.state = body.pack.state
                                    item.info = body.pack.info
                                    item.progrossValue = body.progressBar
                                }
                            })
                        } else if (this.pageSize > this.tableData.length) {
                            this.tableData.unshift({
                                id: body.pack.id,
                                fileName: body.pack.fileName,
                                medicalSum: body.pack.medicalSum,
                                trueSum: body.pack.trueSum,
                                falseSum: body.pack.falseSum,
                                createTime: body.pack.createTime,
                                createUserName: body.pack.createUserName,
                                state: body.pack.state,
                                info: body.pack.info,
                                progrossValue: body.progressBar
                            })
                            this.total++
                        }
                    }
                })
            },
            /**
             * 初始化页面参数
             */
            initPage () {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                this.currentPage = query.pageIndex || 1
                this.pageSize = query.pageSize || 20
            },
            /**
             * 翻页
             */
            changePage () {
                this.submitSearch()
            },
            /**
             * 提交查询
             * @param form 筛选条件
             */
            submitSearch (form) {
                let data = form || this.globalForm
                this.globalForm = data
                let params = {
                    ...data,
                    pageSize: this.pageSize,
                    pageIndex: this.currentPage,
                    orderBy: this.sortType
                }
                delete params.department
                delete params.depName
                this.tableData = []
                this.getList(params)
                this.setGetStore(this.$route.name, params)
            },
            /**
             * 查询列表
             * @param params 请求参数
             */
            getList (params) {
                this.emptyText = '加载中...'
                if (this.getSession(this.$route.name, 'getImportList') && this.useStore) {
                    this.useStore = false
                    let res = this.getSession(this.$route.name, 'getImportList')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.total = res.data.total
                        this.tableData = res.data.rows
                        this.sortMap = res.data.maps
                    }
                } else {
                    getImportList(params).then(res => {
                        this.useStore = false
                        this.setSession(this.$route.name, {getImportList: res})
                        this.emptyText = '暂无数据'
                        if (res.code.toString() === '200') {
                            this.total = res.data.total
                            this.tableData = res.data.rows
                            this.sortMap = res.data.maps
                        }
                    }).catch(() => {
                        this.emptyText = '暂无数据'
                    })
                }
            },
            /**
             * 排序修改
             * @param colData.prop 排序参数
             * @param colData.order 正序倒序 ascending 升序 descending 降序 null 不排序默认
             */
            sortChange (colData) {
                this.sortType = getSortString(colData, this.sortMap)
                this.tableData = []
                this.currentPage = 1
                this.submitSearch()
            },
            /**
             * 显示上传弹框
             * @param index 索引
             * @param row 行数据
             */
            showDialog (index, row) {
                this.limit = row ? 1 : 5
                this.fileDataId = row ? row.id : ''
                this.fileList = []
                this.dialogVisible = true
            },
            /**
             * 关闭前
             */
            handleClose () {
                if (this.fileList.length > 0) {
                    this.$confirm('还未上传，是否关闭？')
                        .then(() => {
                            this.closeDialog()
                        })
                        .catch(() => {
                        })
                } else {
                    this.closeDialog()
                }
            },
            /**
             * 关闭弹窗
             */
            closeDialog () {
                this.fileList = []
                this.dialogVisible = false
            },
            /**
             * 下载模板
             */
            downloadTemplate () {
                window.location.href = `${process.env.BASE_URL}医保结算结果列表模板文件.xlsx`
            },
            /**
             * 删除文件
             * @param uid 要删除的文件
             */
            removeFile (uid) {
                let index = this.fileList.findIndex(item => {
                    return item.uid === uid
                })
                if (index !== -1) {
                    this.fileList.splice(index, 1)
                }
            },
            /**
             * 提交文件
             */
            submitFileList () {
                let params = new FormData()
                params.append('orgId', this.globalForm.orgId)
                if (this.fileDataId !== '') {
                    params.append('id', this.fileDataId)
                }
                for (let i = 0; i < this.fileList.length; i++) {
                    params.append('file', this.fileList[i].raw, this.fileList[i].raw.name)
                }
                groupUploadFiles(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.closeDialog()
                    } else {
                        this.$message.error(res.message)
                    }
                })
            },
            /**
             * 删除数据
             * @param index 索引
             * @param row 行数据
             */
            deleteRow (index, row) {
                let text = `你确定删除"${row.fileName}"文件吗?删除后将不能恢复，请谨慎操作!`
                this.$confirm(text, '删除提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(() => {
                    let params = {
                        id: row.id
                    }
                    delImportList(params).then(res => {
                        if (res.code.toString() === '200') {
                            this.$message.success('删除成功!')
                            this.submitSearch()
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                })
            },
            /**
             * 前往结算列表
             * @param row 行数据
             * @param way 点击方式
             */
            toBillingList (row, way) {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (way === 1) {
                    this.setGetStore('BillingListIndex', {...query, rid: row.id})
                } else {
                    this.setGetStore('BillingListIndex', {...query, rid: row.id, state: 1})
                }
                this.$router.push({name: 'BillingListIndex'})
            },
            /**
             * 前往对比结果
             * @param row 行数据
             */
            toCompareResults (row) {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                this.setGetStore('CompareResultsIndex', {...query, rid: row.id, GState: ''})
                this.$router.push({name: 'CompareResultsIndex'})
            }
        },
        components: {
            uploadFile
        },
        filters: {
            getState (val) {
                switch (val) {
                case 0:
                    return '失败'
                case 1:
                    return '处理中'
                case 2:
                    return '成功'
                }
            }
        },
        beforeDestroy () {
            this.connection = null
            window.onresize = null
        }
    }
</script>

<style scoped lang="scss">
    .join-drgs-container {
        .el-form-item--mini.el-form-item {
            margin-bottom: 10px;
        }
        .name-input {
            width: 80px;
        }
        .select-input {
            width: 100px;
        }
        .weight-input {
            width: 80px;
        }
        .tables-box {
            background: #fff;
            padding: 10px 10px 0;
            position: relative;
            .pagination-container {
                position: absolute;
                top: 0;
                right: 0;
            }
        }
    }

    /deep/ .el-dialog {
        min-width: 600px;
        .el-dialog__body {
            padding: 10px;
            .content {
                width: 90%;
                margin: 0 auto;
                .template-box {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin: 0 auto 20px;
                    background: #e7f8ff;
                    border: 1px solid #91dfff;
                    border-radius: 5px;
                    padding: 0 10px;
                    i {
                        color: #46a6ff;
                    }
                }
            }
        }
        .el-dialog__footer {
            text-align: right;
        }
    }
</style>
